package data.nanjing.expo.ctrls;

import data.nanjing.expo.common.ExpoConstants;
import data.nanjing.expo.common.Result;
import data.nanjing.expo.models.domain.*;
import data.nanjing.expo.models.domain.dto.ActivityDto;
import data.nanjing.expo.models.domain.dto.ActivityInfoDto;
import data.nanjing.expo.models.domain.dto.FavoriteShow;
import data.nanjing.expo.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zjp on 2018/6/28.
 * QQ：34948062
 * github: https://www.github.com/zjp1029
 * web： http://www.zjp1029.cn
 */
@RestController
@RequestMapping("/api/activity")
public class ActivityCtrl extends BaseCtrl {

    @Autowired
    private ActivityInfoService activityInfoService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private ActivityTagInfoService activityTagInfoService;

    @Autowired
    private ActivityApplyInfoService activityApplyInfoService;

    @Autowired
    private UserFavoriteService userFavoriteService;


    /**
     * 从sysConfig获取行业、标签等信息
     * @param type
     * @return
     */
    @GetMapping("/params/{type}")
    public Result getIndustry(@PathVariable("type") String type) {
        try {
            List<SysConfig> sysConfigList = new ArrayList<>();
            //行业属性
            if ("industry".equalsIgnoreCase(type)) {
                sysConfigList = sysConfigService.findSysConfigByType(ExpoConstants.ACTIVITY_INDUSTRY);
            }else if ("tag".equalsIgnoreCase(type)) {
                //标签属性
                sysConfigList = sysConfigService.findSysConfigByType(ExpoConstants.ACTIVITY_TAG);
            }
            for (SysConfig sysConfig : sysConfigList) {
                if ("any".equalsIgnoreCase(sysConfig.getCode())) {
                    sysConfigList.remove(sysConfig);
                    break;
                }
            }
            return send(sysConfigList, 1, "OK");
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "获取数据失败!");
        }
    }


    /**
     * 获取活动列表
     * @param status
     * @param request
     * @return
     */
    @GetMapping("/list/{status}")
    public Result getActivityList(@PathVariable("status") String status, HttpServletRequest request,
                                  @RequestParam(name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                  @RequestParam(name = "pageSize", defaultValue = "15") Integer pageSize) {
        try {
            User user = this.getUserFromSession(request);
            if (user == null) {
                return send(-2, "请登录!");
            }
            Map<String, Object> map = new HashMap<>();
            List<ActivityInfo> list = new ArrayList<>();
            int total = 0;
            if (status.equalsIgnoreCase("ing")) {
                list = activityInfoService.selectActivityListByUserIdAndIsWork(user.getId(), pageNumber, pageSize, true);
                total = activityInfoService.selectWorkActivityCountByUserId(user.getId());
            }else {
                list = activityInfoService.selectActivityListByUserIdAndIsWork(user.getId(), pageNumber, pageSize,false);
                total = activityInfoService.selectEndActivityCountByUserId(user.getId());
            }
            map.put("total", total);
            map.put("data", list);
            return send(map, 1, "OK");
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "获取活动列表失败");
        }
    }

    /**
     * 添加活动
     * @param
     * @param
     * @param request
     * @return
     */
    @PostMapping("/add")
    public Result addActivity(@Valid ActivityDto activityDto, HttpServletRequest request) {
        try {
            User user = super.getUserFromSession(request);
            if (user == null) {
                return send(-2, "请先登录!");
            }
            ActivityInfo activityInfo = new ActivityInfo("offline", activityDto.getActivityContent(), activityDto.getActivityName(),
                    activityDto.getProvince(), activityDto.getCity(),activityDto.getArea(), ListToString(activityDto.getIndustry()), "yes", activityDto.getImagePath(),
                    activityDto.getAllowNum(), activityDto.getStartTime(), activityDto.getEndTime());
            activityInfo.setUserId(user.getId());
            ActivityInfoDetail activityInfoDetail = new ActivityInfoDetail(activityDto.getActivityGuide(), activityDto.getStreet(),
                    activityDto.getIntroduce(), activityDto.getSchedule(), activityDto.getOrganizations(), activityDto.getLocation(), activityDto.getGuestInfo());
            Integer activityId = activityInfoService.addActivityInfo(activityInfo, activityInfoDetail);

            //如果标签不为空
            if (activityDto.getTags() != null && activityDto.getTags().size() > 0) {
                saveActivityTags(activityDto.getTags(), activityId);
            }
            return send(1, "发布成功");
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "发布活动出错了!");
        }
    }


    /**
     * 行业内容转换
     * @param industry
     * @return
     */
    private String ListToString(List<String> industry) {
        if (industry == null) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0;i < industry.size(); i++) {
            if ( i != 0) {
                builder.append(",").append(industry.get(i));
            }else {
                builder.append(industry.get(i));
            }
        }
        return builder.toString();
    }


    /**
     * 将标签保存，更新与保存新增通用
     * @param tags
     * @param activityId
     */
    private void saveActivityTags(List<Integer> tags, Integer activityId) {
        List<SysConfig> sysConfigs = sysConfigService.findSysConfigInList(tags);
        List<ActivityTagInfo> tagInfos = new ArrayList<>();
        for (SysConfig s : sysConfigs) {
            ActivityTagInfo a = new ActivityTagInfo();
            a.setActivityId(activityId);
            a.setTagCode(s.getCode());
            a.setTagName(s.getName());
            tagInfos.add(a);
        }
        activityTagInfoService.addActivityTagInfo(tagInfos);
    }

    /**
     * 修改活动时获取活动详情
     * @param activityId
     * @return
     */
    @GetMapping("/detail/{activityId}")
    public Result getActivityDetail(@PathVariable("activityId") Integer activityId, HttpServletRequest request) {
        try {
            User user = this.getUserFromSession(request);
            if (user == null) {
                return send(-2, "请先登录");
            }
            if(activityId==-1){
                return send(2,"");
            }
            ActivityInfoDto activityInfoDto = activityInfoService.selectActivityDetailInfoById(activityId);
            if (activityInfoDto == null) {
                return send(-1, "活动已结束或取消!");
            }
            if (!activityInfoDto.getUserId().equals(user.getId())) {
                return send(-3, "您没有权限修改此活动!");
            }
            return send(activityInfoDto, 1, "OK");
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "获取失败!");
        }
    }

    /**
     * 修改活动
     * @param activityDto
     * @param request
     * @return
     */
    @PostMapping("/update")
    public Result updateActivity(@Valid ActivityDto activityDto, HttpServletRequest request) {
        try {
            User user = this.getUserFromSession(request);
            if (user == null) {
                return send(-2, "请先登录!");
            }
            if (activityDto.getId() == null || activityDto.getUserId() == null) {
                return send(-1, "修改出错!");
            }
            if (!user.getId().equals(activityDto.getUserId())) {
                return send(-3, "您无权限修改此活动");
            }

            ActivityInfo activityInfo = new ActivityInfo("offline", activityDto.getActivityContent(), activityDto.getActivityName(),
                    activityDto.getProvince(), activityDto.getCity(),activityDto.getArea(), ListToString(activityDto.getIndustry()), "yes", activityDto.getImagePath(),
                    activityDto.getAllowNum(), activityDto.getStartTime(), activityDto.getEndTime());
            activityInfo.setUserId(user.getId());
            activityInfo.setId(activityDto.getId());
            ActivityInfoDetail activityInfoDetail = new ActivityInfoDetail(activityDto.getActivityGuide(), activityDto.getStreet(),
                    activityDto.getIntroduce(), activityDto.getSchedule(), activityDto.getOrganizations(), activityDto.getLocation(), activityDto.getGuestInfo());
            activityInfoDetail.setActivityId(activityDto.getId());
            activityInfoService.updateActivityInfo(activityInfo, activityInfoDetail);
            //标签更新
            activityTagInfoService.deleteActivityTagByActivityId(activityInfo.getId());
            if (activityDto.getTags() != null && activityDto.getTags().size() > 0) {
                saveActivityTags(activityDto.getTags(), activityInfo.getId());
            }
            return send(1, "修改成功!");
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "修改活动出错了!");
        }
    }


    /**
     * 取消活动
     * @param activityId
     * @return
     */
    @PostMapping("/cancel")
    public Result cancelActivity(@RequestParam("activityId") Integer activityId, HttpServletRequest request) {
        try {
            User user = this.getUserFromSession(request);
            if (user == null) {
                return send(-1, "请登录!");
            }
            activityInfoService.updateActivityStatus(activityId, "cancel");
            return send(1, "取消成功");
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "取消活动失败");
        }
    }


    /**
     * 收藏和取消收藏，共用一个接口
     * @param favorite
     * @param request
     * @return
     */
    @PostMapping("/favorite")
    public synchronized Result favoriteActivity(@Valid UserFavorite favorite, HttpServletRequest request) {
        try {
            User user = this.getUserFromSession(request);
            if (user == null) {
                return send(-2,"请登录");
            }
            boolean isFavorite = userFavoriteService.isFavorite(user.getId(), ExpoConstants.FAVORITE_ACTIVITY, favorite.getFavoriteId());
            //已经收藏，则取消收藏
            if (isFavorite) {
                userFavoriteService.deleteFavorite(user.getId(), ExpoConstants.FAVORITE_ACTIVITY, favorite.getFavoriteId());
                return send(1, "收藏");
            }else {
                favorite.setFavoriteType(ExpoConstants.FAVORITE_ACTIVITY);
                favorite.setUserId(user.getId());
                userFavoriteService.addActivityFavorite(favorite);
                return send(1, "已收藏");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "操作失败");
        }
    }


    /**
     * 活动报名
     * 因报名是除了添加一条报名信息外，还要在活动中的报名人数加一
     * 现阶段处理办法: 对该方法进行加锁处理
     * 报名与取消报名
     * @return
     */
    @PostMapping("/apply")
    public synchronized Result applyActivity(@Valid ActivityApplyInfo activityApplyInfo, HttpServletRequest request) {
        try {
            User user = this.getUserFromSession(request);
            if (user == null) {
                return send(-2, "请先登录!");
            }
            boolean isApply = activityApplyInfoService.isApply(user.getId(), activityApplyInfo.getActivityId());
            if (isApply) {  //如果已经报名了，就取消报名
                activityApplyInfoService.deleteActivityApplyInfo(user.getId(), activityApplyInfo.getActivityId());
                return send(1, "取消报名成功");
            }else { //未报名则报名
                //先判断报名人数是否已满
                ActivityInfo activityInfo = activityInfoService.selectActivityInfoById(activityApplyInfo.getActivityId());
                if (activityInfo.getAllowNum() > activityInfo.getApplyNumber()) {
                    activityApplyInfo.setUserId(user.getId());
                    activityApplyInfoService.addApplyNumber(activityApplyInfo);
                    return send(1, "报名成功");
                }else {
                    return send(2006, "报名已满");
                }

            }
        }catch (Exception e) {
            e.printStackTrace();
            return send(-1, "报名失败");
        }
    }

    /**
     * 查询我的报名信息
     * 加入分页
     * @param request
     * @return
     */
    @GetMapping("/apply/list")
    public Result getApplyList(HttpServletRequest request,
                               @RequestParam(name = "pageNumber", defaultValue = "1") Integer pageNumber,
                               @RequestParam(name = "pageSize", defaultValue = "15") Integer pageSize) {
        User user = this.getUserFromSession(request);
        if (user == null) {
            return send(-2, "请登录");
        }
        Map<String, Object> map = new HashMap<>();
        Integer count = activityApplyInfoService.selectApplyCountByUserId(user.getId());
        List<FavoriteShow> list = new ArrayList<>();
        if (count != 0) {
            list = activityApplyInfoService.selectApplyListByUserId(user.getId(), pageNumber, pageSize);
        }
        map.put("total", count);
        map.put("data", list);
        return send(map, 1, "OK");
    }

    /**
     * 查询我的收藏信息
     * @param request
     * @return
     */
    @GetMapping("/favorite/list")
    public Result getFavoriteList(HttpServletRequest request,
                                  @RequestParam(name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                  @RequestParam(name = "pageSize", defaultValue = "15") Integer pageSize) {
        User user = this.getUserFromSession(request);
        if (user == null) {
            return send(-2, "请登录");
        }
        Map<String, Object> map = new HashMap<>();
        Integer count = userFavoriteService.selectActivityFavoriteCountByUserId(user.getId(), ExpoConstants.FAVORITE_ACTIVITY);
        List<FavoriteShow> list = new ArrayList<>();
        if (count != 0) {
            list = userFavoriteService.selectActivityFavoriteByUserId(user.getId(), pageNumber, pageSize, ExpoConstants.FAVORITE_ACTIVITY);
        }
        map.put("total", count);
        map.put("data", list);
        return send(map, 1, "OK");
    }

    /**
     * 获取报名状态
     * @param activityId
     * @return
     */
    @GetMapping("/apply/full/{activityId}")
    public Result isFull(@PathVariable("activityId") Integer activityId) {
        if (activityId == null) {
            return send(-1, "获取数据失败");
        }
        ActivityInfo activityInfo = activityInfoService.selectActivityInfoById(activityId);
        if (activityInfo.getApplyNumber() < activityInfo.getAllowNum()) {
            return send(2005, "报名未满");
        }else {
            return send(2006, "报名已满");
        }
    }


    /**
     * 获取活动的报名人
     * @param activityId
     * @return
     */
    @GetMapping("/apply/people/{activityId}")
    public Result activityApplyDetail(@PathVariable("activityId") Integer activityId,
                                      @RequestParam(name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                      @RequestParam(name = "pageSize", defaultValue = "15") Integer pageSize) {
        if (activityId == null) {
            return send(-1, "获取数据失败");
        }
        int count = activityApplyInfoService.selectApplyListCountByActivityId(activityId);
        List<ActivityApplyInfo> list = new ArrayList<>();
        if (count > 0) {
            list = activityApplyInfoService.selectApplyListByActivityId(activityId, pageNumber, pageSize);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", count);
        map.put("data", list);
        return send(map, 1, "获取数据成功");
    }
}
